package com.example.dzbsh.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.example.dzbsh.model.Admin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.dzbsh.service.AdminService;
import com.example.dzbsh.util.BooleanMessage;
import com.example.dzbsh.util.CreateXLS;
import com.example.dzbsh.util.JsonResult;
import com.example.dzbsh.util.StringHandle;


@RestController
@RequestMapping("admin")
public class AdminController {
	
	@Value("${userfilepath}")
	private String userfilepath;

    @Resource
    AdminService ddAdminService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    
    @RequestMapping("login")
    public JsonResult<?> login(
            @RequestParam("zhanghao") String ppLoginName,
            @RequestParam("password") String ppLoginPassword,
            HttpServletRequest request){
        try {
            ppLoginName = ppLoginName.trim();
            ppLoginPassword = ppLoginPassword.trim();
            List<Map<String, Object>> mmYonghuList = ddAdminService.findByLoginnameAndPassword(ppLoginName, ppLoginPassword);
            if(mmYonghuList.size()==0){
                return JsonResult.getErrorResult("登录失败！登录名密码错误或账号无效!");
            }
            
            Map<String, Object> mmYonghuMap = mmYonghuList.get(0);
            String mmAdminId =mmYonghuMap.get("adminid")==null?"":mmYonghuMap.get("adminid").toString();
            String mmDeptId = mmYonghuMap.get("deptid")==null?"":mmYonghuMap.get("deptid").toString();
            String mmDeptName = mmYonghuMap.get("danweiduiwaimingcheng")==null?"":mmYonghuMap.get("danweiduiwaimingcheng").toString();
            String mmXuliebianma = mmYonghuMap.get("xuliebianma")==null?"":mmYonghuMap.get("xuliebianma").toString();

            // 登录成功,记录session
            HttpSession session = request.getSession();
            session.setAttribute("AdminId", mmAdminId);
            session.setAttribute("DeptId", mmDeptId);
            session.setAttribute("DeptName", mmDeptName);
            session.setAttribute("Xuliebianma", mmXuliebianma);

            return JsonResult.getSuccessResult("登录成功");
        }catch(Exception e) {
            e.printStackTrace();
            return JsonResult.getErrorResult("登录失败！");
        }
    }
    
    @RequestMapping("logout")
    public boolean logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("AdminId");
        session.removeAttribute("DeptId");
        session.removeAttribute("DeptName");
        session.removeAttribute("Xuliebianma");
        return true;
    }
    
    //跟据单位查询管理员
    @RequestMapping("find_by_deptid")
    public JsonResult<?> findByDeptid(@RequestParam("deptid") String ppDeptId) {
        try {
            return JsonResult.getSuccessResult(ddAdminService.findByDeptId(ppDeptId));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("AdminController->findCustomByUserid:"+e.getMessage());
            return JsonResult.getErrorResult("根据单位查询单位管理员失败");
        }
    }

    @RequestMapping("find_one")
    public JsonResult<?> find_one(
            @RequestParam("adminid") String ppAdminId
    ){
        try {
            return JsonResult.getSuccessResult(ddAdminService.findOne(ppAdminId));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("AdminController->find_one:"+e.getMessage());
            return JsonResult.getErrorResult("单个单位管理员查询失败");
        }
    }

    @RequestMapping("add")
    public JsonResult<?> add(
           @RequestParam("loginname") String ppLoginName,
            @RequestParam("loginpassword") String ppLoginPassword,
            @RequestParam("truename") String ppTruename,
            @RequestParam("phone") String ppPhone,
            @RequestParam("deptid") String ppDeptId,
            @RequestParam("admintype") int ppAdmintype,
            @RequestParam("isvalid") int ppIsvalid
    ){
        try {
        	
        	if (ddAdminService.findByLoginname(ppLoginName).size()>0) {
				return JsonResult.getErrorResult("已存在该登录名，修改其他登录名");
			}
            Admin mmAdmin=new Admin();
            mmAdmin.setAdminid(UUID.randomUUID().toString());
            BooleanMessage  mmBooleanMessage=checkInputData(mmAdmin,ppLoginName,ppLoginPassword,ppTruename,ppPhone,ppDeptId,ppAdmintype,ppIsvalid);
            if (!mmBooleanMessage.isOk()) {
                return JsonResult.getErrorResult(mmBooleanMessage.getMessage().toString());
            }
            mmAdmin = (Admin) mmBooleanMessage.getMessage();

            return ddAdminService.add(mmAdmin) == true ? JsonResult
                    .getSuccessResult("添加成功") : JsonResult.getErrorResult("添加失败");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("AdminController->add:"+e.getMessage());
            return JsonResult.getErrorResult("单位管理员添加失败");
        }
    }

    @RequestMapping("modify")
    public JsonResult<?> modify(
            @RequestParam("adminid") String ppAdminId,
            @RequestParam("loginname") String ppLoginName,
            @RequestParam("loginpassword") String ppLoginPassword,
            @RequestParam("truename") String ppTruename,
            @RequestParam("phone") String ppPhone,
            @RequestParam("deptid") String ppDeptId,
            @RequestParam("admintype") int ppAdmintype,
            @RequestParam("isvalid") int ppIsvalid
    ){
        try {

            Admin mmAdmin=ddAdminService.findOne(ppAdminId);
            if (mmAdmin==null){
                return JsonResult.getErrorResult("暂无该管理员");
            }
            if (ddAdminService.findExitByLoginname(ppLoginName, ppAdminId).size()>0) {
				return JsonResult.getErrorResult("已存在该登录名，请修改其他登录名");
			}

            BooleanMessage  mmBooleanMessage=checkInputData(mmAdmin,ppLoginName,ppLoginPassword,ppTruename,ppPhone,ppDeptId,ppAdmintype,ppIsvalid);
            if (!mmBooleanMessage.isOk()) {
                return JsonResult.getErrorResult(mmBooleanMessage.getMessage().toString());
            }
            mmAdmin = (Admin) mmBooleanMessage.getMessage();

            return ddAdminService.modify(mmAdmin) == true ? JsonResult
                    .getSuccessResult("修改成功") : JsonResult.getErrorResult("修改失败");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("AdminController->modify:"+e.getMessage());
            return JsonResult.getErrorResult("单位管理员修改失败");
        }
    }

    // 删除单个单位管理员
    @RequestMapping("delete")
    public JsonResult<?> delete(@RequestParam("adminid") String ppAdminId) {
        try {
            if ("".equals(ppAdminId)) {
                return JsonResult.getErrorResult("管理员id不能为空");
            }

            Admin mmAdmin=ddAdminService.findOne(ppAdminId);
            if (mmAdmin == null) {
                return JsonResult.getErrorResult("要删除的管理员不存在");
            }

            return ddAdminService.delete(ppAdminId) == true ? JsonResult.getSuccessResult("删除成功") : JsonResult.getErrorResult("删除失败");
        } catch (Exception e) {
            logger.error("AdminController->delete:"+e.getMessage());
            return JsonResult.getErrorResult("单位管理员删除失败");
        }
    }

    private BooleanMessage checkInputData(Admin mmAdmin,
                                          String ppLoginName,String ppLoginPassword,
                                          String ppTruename,String ppPhone,
                                          String ppDeptId,int ppAdmintype,
                                          int ppIsvalid) {

        ppLoginName=ppLoginName.trim();
        ppLoginPassword=ppLoginPassword.trim();
        ppTruename=ppTruename.trim();
        ppPhone=ppPhone.trim();
        ppDeptId=ppDeptId.trim();

        if ("".equals(ppDeptId)) {
            return BooleanMessage.getErrorMessage("单位id不能为空");
        }
        if ("".equals(ppIsvalid)) {
            return BooleanMessage.getErrorMessage("是否有效不能为空");
        }
        if (StringHandle.getStringByteLength(ppLoginName) > 200) {
            return BooleanMessage.getErrorMessage("登录名不能超过200字节");
        }
        if (StringHandle.getStringByteLength(ppLoginPassword) > 200) {
            return BooleanMessage.getErrorMessage("登录密码不能超过200字节");
        }
        if (StringHandle.getStringByteLength(ppTruename) > 200) {
            return BooleanMessage.getErrorMessage("姓名不能超过200字节");
        }
        if (StringHandle.getStringByteLength(ppPhone) > 50) {
            return BooleanMessage.getErrorMessage("电话不能超过50字节");
        }
        if (StringHandle.getStringByteLength(ppDeptId) > 50) {
            return BooleanMessage.getErrorMessage("单位id不能超过50字节");
        }
        if (StringHandle.getStringByteLength(String.valueOf(ppAdmintype)) > 11) {
            return BooleanMessage.getErrorMessage("管理员类型不能超过11字节");
        }
        if (StringHandle.getStringByteLength(String.valueOf(ppIsvalid)) > 11) {
            return BooleanMessage.getErrorMessage("是否有效不能超过11字节");
        }


        mmAdmin.setLoginname(ppLoginName);
        mmAdmin.setLoginpassword(ppLoginPassword);
        mmAdmin.setPhone(ppPhone);
        mmAdmin.setTruename(ppTruename);
        mmAdmin.setDeptid(ppDeptId);
        mmAdmin.setAdmintype(ppAdmintype);
        mmAdmin.setIsvalid(ppIsvalid);
        return BooleanMessage.getSuccessMessage(mmAdmin);
    }
    
    @RequestMapping("admin_huizongbiao")
	public void adminHuizongbiao(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub

		List<List<String>> mmResultList = new ArrayList<List<String>>(); 
		List<String> mmTitleList = new ArrayList<String>(); 

		mmTitleList.add("序号");
		mmTitleList.add("单位对外名称"); 
		mmTitleList.add("单位对内名称"); 
		mmTitleList.add("姓名"); 
		mmTitleList.add("登录账号"); 
		mmTitleList.add("登录密码");
		mmTitleList.add("电话");
		mmTitleList.add("管理员权限");

		mmResultList.add(mmTitleList);

		List<Map<String, Object>> mmHuizongbiaoList = ddAdminService.findCustomAll();

		int mmRenyuanshu = mmHuizongbiaoList.size(); 
		if(mmRenyuanshu > 0) { 
			for(int i = 0; i <mmRenyuanshu; i++) { 
				Map<String, Object> mmHuizongbiaoMap = mmHuizongbiaoList.get(i); 
				String mmXuhao = String.valueOf(i + 1); 
				String mmTruename = mmHuizongbiaoMap.get("truename") == null ? "" : mmHuizongbiaoMap.get("truename").toString();
				String mmLoginname = mmHuizongbiaoMap.get("loginname") == null ? "" : mmHuizongbiaoMap.get("loginname").toString();
				String mmLoginpassword =mmHuizongbiaoMap.get("loginpassword") == null ? "" :mmHuizongbiaoMap.get("loginpassword").toString(); 
				String mmPhone = mmHuizongbiaoMap.get("phone") == null ? "" : mmHuizongbiaoMap.get("phone").toString();
				String mmAdmintype = mmHuizongbiaoMap.get("admintype") == null ? "" : mmHuizongbiaoMap.get("admintype").toString();

				String mmDuiwaimingcheng = mmHuizongbiaoMap.get("danweiduiwaimingcheng") == null ? "" : mmHuizongbiaoMap.get("danweiduiwaimingcheng").toString();

				String mmDuineimingcheng = mmHuizongbiaoMap.get("danweiduineimingcheng") == null ? "" : mmHuizongbiaoMap.get("danweiduineimingcheng").toString();
				
				if ("2".equals(mmAdmintype)) {
					mmAdmintype = "录入";
				}else {
					mmAdmintype = "查看";
				}


				List<String> mmRenyuanList = new ArrayList<String>();
				mmRenyuanList.add(mmXuhao);
				mmRenyuanList.add(mmDuiwaimingcheng); 
				mmRenyuanList.add(mmDuineimingcheng); 
				mmRenyuanList.add(mmTruename); 
				mmRenyuanList.add(mmLoginname); 
				mmRenyuanList.add(mmLoginpassword);
				mmRenyuanList.add(mmPhone);
				mmRenyuanList.add(mmAdmintype);

				mmResultList.add(mmRenyuanList); 
			} 
		}

		try { 
			//取出文档存放的根目录，并去除文件最后的斜杠 
			if (userfilepath.endsWith("/")) { 
				userfilepath = userfilepath.substring(0, userfilepath.length()-1); 
			}

			SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd");
			String mmSavePath = userfilepath +  "/temp/jingshangjianguan/admin/"+mmDateFormat.format(new Date()) + "/";

			CreateXLS.createExcel(mmResultList, mmSavePath,  "Alladmin.xls",
					"huizongbiao", request, response); 

		} 
		catch (Exception e) { 
			logger.error("AdminController -> admin_huizongbiao: "+e.getMessage());
		}

	}
    
    @RequestMapping("admin_huizongbiao_by_deptid")
	public void adminHuizongbiaoByDeptId(@RequestParam("deptid") String ppDeptId,HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub

		List<List<String>> mmResultList = new ArrayList<List<String>>(); 
		List<String> mmTitleList = new ArrayList<String>(); 

		mmTitleList.add("序号");
		mmTitleList.add("单位对外名称"); 
		mmTitleList.add("单位对内名称"); 
		mmTitleList.add("姓名"); 
		mmTitleList.add("登录账号"); 
		mmTitleList.add("登录密码");
		mmTitleList.add("电话");
		mmTitleList.add("管理员权限");

		mmResultList.add(mmTitleList);

		List<Map<String, Object>> mmHuizongbiaoList = ddAdminService.findCustomByDeptId(ppDeptId);

		int mmRenyuanshu = mmHuizongbiaoList.size(); 
		if(mmRenyuanshu > 0) { 
			for(int i = 0; i <mmRenyuanshu; i++) { 
				Map<String, Object> mmHuizongbiaoMap = mmHuizongbiaoList.get(i); 
				String mmXuhao = String.valueOf(i + 1); 
				String mmTruename = mmHuizongbiaoMap.get("truename") == null ? "" : mmHuizongbiaoMap.get("truename").toString();
				String mmLoginname = mmHuizongbiaoMap.get("loginname") == null ? "" : mmHuizongbiaoMap.get("loginname").toString();
				String mmLoginpassword =mmHuizongbiaoMap.get("loginpassword") == null ? "" :mmHuizongbiaoMap.get("loginpassword").toString(); 
				String mmPhone = mmHuizongbiaoMap.get("phone") == null ? "" : mmHuizongbiaoMap.get("phone").toString();
				String mmAdmintype = mmHuizongbiaoMap.get("admintype") == null ? "" : mmHuizongbiaoMap.get("admintype").toString();

				String mmDuiwaimingcheng = mmHuizongbiaoMap.get("danweiduiwaimingcheng") == null ? "" : mmHuizongbiaoMap.get("danweiduiwaimingcheng").toString();

				String mmDuineimingcheng = mmHuizongbiaoMap.get("danweiduineimingcheng") == null ? "" : mmHuizongbiaoMap.get("danweiduineimingcheng").toString();
				
				if ("2".equals(mmAdmintype)) {
					mmAdmintype = "录入";
				}else {
					mmAdmintype = "查看";
				}


				List<String> mmRenyuanList = new ArrayList<String>();
				mmRenyuanList.add(mmXuhao);
				mmRenyuanList.add(mmDuiwaimingcheng); 
				mmRenyuanList.add(mmDuineimingcheng); 
				mmRenyuanList.add(mmTruename); 
				mmRenyuanList.add(mmLoginname); 
				mmRenyuanList.add(mmLoginpassword);
				mmRenyuanList.add(mmPhone);
				mmRenyuanList.add(mmAdmintype);

				mmResultList.add(mmRenyuanList); 
			} 
		}

		try { 
			//取出文档存放的根目录，并去除文件最后的斜杠 
			if (userfilepath.endsWith("/")) { 
				userfilepath = userfilepath.substring(0, userfilepath.length()-1); 
			}

			SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd");
			String mmSavePath = userfilepath +  "/temp/jingshangjianguan/admin/"+mmDateFormat.format(new Date()) + "/";

			CreateXLS.createExcel(mmResultList, mmSavePath,  ppDeptId+"admin.xls",
					"huizongbiao", request, response); 

		} 
		catch (Exception e) { 
			logger.error("AdminController -> admin_huizongbiao_by_dept: "+e.getMessage());
		}

	}

}
